package com.neighbor.neighborhooduser.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neighbor.neighborhooduser.pojo.Messages;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.service.IMessagesService;
import com.neighbor.neighborhooduser.service.IUsersService;
import com.neighbor.neighborhooduser.utils.JwtUtils;
import com.neighbor.neighborhooduser.utils.ReOpe;
import com.neighbor.neighborhooduser.utils.RedisUtils;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;
/**
 * <p>
 * 用户聊天消息表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@RestController
@RequestMapping("/messages")
public class MessagesController {

    @Autowired
    IUsersService usersService;

    @Autowired
    ReOpe reOpe;    //方法


    @Autowired
    IMessagesService messagesService;   //消息表代理对象

    /**
     *      根据会话的双方对象从数据库中获取消息
     * @param friendId  对方id
     * @param request 从请求中获取用户id
     * @return  消息(List<Messages>)
     */
    @RequestMapping("selSession")
    ResponseMsg selSession(String friendId, HttpServletRequest request){
        //验证token
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if(responseMsg.getCode() == ResponseMsg.SUCCESS) {
            String userId = ((Users) responseMsg.getData()).getUserId().toString();
            QueryWrapper<Messages> wrapper = new QueryWrapper<>();
            //查询条件，两者的对话
            wrapper.nested(wq -> wq.eq("sender_id", friendId).eq("receiver_id", userId))
                    .or(wq -> wq.eq("sender_id", userId).eq("receiver_id", friendId));
            //得到结果集(List)
            List<Messages> messages = messagesService.list(wrapper);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "获得会话消息", messages);
        }
        return responseMsg;
    }

    /**
     *      根据用户搜索模糊查询得到聊天记录
     * @param content   模糊查询信息
     * @param request   请求体
     * @return  聊天记录
     */
    @RequestMapping("selMessageByFriend")
    ResponseMsg selMessageByFriend(String content,HttpServletRequest request){
        //验证token
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if(responseMsg.getCode() == ResponseMsg.SUCCESS){
            Users users = (Users) responseMsg.getData();
            List<Messages> messages = messagesService.selByFriend(users.getUserId(),content);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"获取聊天记录",messages);
        }
        return responseMsg;
    }

    /**
     *      发送消息后的保存
     * @param messages  发送的消息
     * @return  是否发送成功
     */
    @RequestMapping("add")
    ResponseMsg add(Messages messages,HttpServletRequest request){
        //验证token
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() == ResponseMsg.SUCCESS) {
            Users users = (Users) responseMsg.getData();
            messages.setSenderId(users.getUserId());
            return messagesService.save(messages) ? ResponseMsg.success("发送成功") :
                    ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "发送失败");
        }
        return responseMsg;
    }


    /**
     * 获取用户的所有聊天列表（包含聊天对象信息和最近一条消息）
     * @param request HTTP请求对象，用于验证token
     * @return 包含聊天列表的响应信息，按最近消息时间降序排列
     */
    @RequestMapping("selMessageByUserId")
    public ResponseMsg selMessageByUserId(HttpServletRequest request) {
        // 验证token
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() == ResponseMsg.SUCCESS) {
            Users currentUser = (Users) responseMsg.getData();

            // 查询与当前用户相关的所有消息
            QueryWrapper<Messages> wrapper = new QueryWrapper<>();
            wrapper.eq("sender_id", currentUser.getUserId())
                    .or()
                    .eq("receiver_id", currentUser.getUserId())
                    .orderByDesc("created_at"); // 按时间降序排列

            List<Messages> allMessages = messagesService.list(wrapper);

            // 使用Map来存储每个聊天对象的最新消息
            Map<Integer, Messages> latestMessagesMap = new HashMap<>();
            Set<Integer> chatUserIds = new HashSet<>();

            for (Messages message : allMessages) {
                // 确定聊天对象的ID（排除当前用户自己）
                Integer chatUserId = message.getSenderId().equals(currentUser.getUserId())
                        ? message.getReceiverId()
                        : message.getSenderId();

                chatUserIds.add(chatUserId);

                // 只保留每个聊天对象的最新消息
                if (!latestMessagesMap.containsKey(chatUserId) ||
                        message.getCreatedAt().after(latestMessagesMap.get(chatUserId).getCreatedAt())) {
                    latestMessagesMap.put(chatUserId, message);
                }
            }

            // 查询所有聊天对象的用户信息
            if (!chatUserIds.isEmpty()) {
                List<Users> chatUsers = usersService.listByIds(chatUserIds);
                Map<Integer, Users> userMap = chatUsers.stream()
                        .collect(Collectors.toMap(Users::getUserId, user -> user));

                // 构建返回结果
                List<Map<String, Object>> result = new ArrayList<>();
                for (Integer userId : chatUserIds) {
                    Map<String, Object> chatInfo = new HashMap<>();
                    chatInfo.put("chatUser", userMap.get(userId)); // 聊天对象信息
                    chatInfo.put("latestMessage", latestMessagesMap.get(userId)); // 最新消息
                    result.add(chatInfo);
                }

                // 按最新消息时间排序（最近的在前）
                result.sort((a, b) -> {
                    Date dateA = ((Messages) a.get("latestMessage")).getCreatedAt();
                    Date dateB = ((Messages) b.get("latestMessage")).getCreatedAt();
                    return dateB.compareTo(dateA); // 降序排列
                });

                responseMsg.setData(result);
            } else {
                responseMsg.setData(new ArrayList<>());
            }
        }
        return responseMsg;
    }
}
